﻿#include "audio/ext.h"
#include "stb/vorbis.h"

using namespace std;
using namespace anip::audio;

Waveform* Waveform::fromOGG(const string& filename)
{
	Waveform* w = new Waveform();
	w->_length = stb_vorbis_decode_filename(filename.c_str(),
		&w->_channels, &w->_sampleRate, &w->_data);
	if (w->_length == -1)
		throw runtime_error("Erroring reading OGG audio file");
	return w;
}

bool Waveform::Instance::read(double* dest, unsigned int nSamples, unsigned int start)
{
	memset(dest, 0, nSamples * _wav._channels * sizeof(double));
	if ((int)(start + nSamples) < _wav._length)
	{
		int n = nSamples * _wav._channels;
		for (int i = 0; i < n; i++)
			dest[i] = _wav._data[start * _wav._channels + i] / (double)SHRT_MAX;
		return true;
	} else return false;
}

double anip::audio::Waveform::getAmplitude(double time)
{
	const int span = 600;
	int realSpan = span * _channels;

	int i = (int)(time * _sampleRate * _channels);
	if (i + realSpan >= _length * _channels)
		return 0.0;

	long sum = 0;
	for (int j = 0; j < realSpan; j++)
		sum += _data[i + j];
	return sum / (double)realSpan / SHRT_MAX;
}